package com.prig.base.service;

import cn.hutool.core.util.StrUtil;
import com.prig.base.DTO.input.PageKeywordSortDto;
import com.prig.base.entity.Admin;
import com.prig.base.repository.AdminRepository;
import com.prig.base.util.ChangeType;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdminService {

    private AdminRepository adminRepository;
    @Autowired
    public AdminService(AdminRepository adminRepository) {
        this.adminRepository = adminRepository;
    }

    public String md5DigestAsHex(Admin admin){
        return new SimpleHash("MD5", admin.getPassword(), admin.getAccount(), 2).toHex();
    }

    public Admin saveAdmin(Admin admin){
        return saveAdmin(admin,false);
    }
    public Admin saveAdmin(Admin admin,boolean password){
        if (admin.getId() == 0L || password){
            admin.setPassword(md5DigestAsHex(admin));
        }
        return  adminRepository.save(admin);
    }

    public Admin getAdmin(Admin admin){
        if (admin.getId()>0){
            return adminRepository.findById(admin.getId()).orElse(null);
        }
        if (admin.getPassword() == null || admin.getPassword().isEmpty()){
            return adminRepository.findByAccount(admin.getAccount());
        }
        return adminRepository.findByAccountAndPassword(admin.getAccount(),md5DigestAsHex(admin));
    }



    public Page getAdmin(PageKeywordSortDto dto){
        Pageable pageable = PageRequest.of(dto.getSQLPage(),dto.getLimit(),dto.getSort());
        if(StrUtil.isNotBlank(dto.getKeyword())){
            return adminRepository.findAll(((root, criteriaQuery, criteriaBuilder) -> {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(
                        criteriaBuilder.and(
                                criteriaBuilder.like(
                                        root.get("account"),"%"+dto.getKeyword()+"%"
                                )
                        )
                );
                return criteriaBuilder.and(
                        predicateList.toArray(new Predicate[predicateList.size()])
                );
            }),pageable);
        }
        return adminRepository.findAll(pageable);
    }

    public void del(String adminIds) {
        adminRepository.deleteByIds(ChangeType.String2Long(adminIds));
    }
}
